package com.chyb.cloud;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

/*注入到Spring容器中，之后会将所有注入到容器中的过滤器进行合并，形成过滤器列表*/
@Component
@Slf4j
/*自定义路由过滤器，指定某一个路由执行的过滤器，无参数的写法（只需要编写apply方法即可，注意config的类型）*/
/*注意命名规范：~GatewayFilterFactory*/
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    static final String BEGIN_TIME = "begin_time";
    @Override
    public GatewayFilter apply(Object config) {
        System.out.println("进入了自定义网关过滤器MyGatewayFilterFactory，status：" + config);
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                exchange.getAttributes().put(BEGIN_TIME, System.currentTimeMillis());
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    Long beginTime = exchange.getAttribute(BEGIN_TIME);
                    URI uri = exchange.getRequest().getURI();
                    if (beginTime != null) {
                        log.info("访问接口主机：{}", uri.getHost());
                        log.info("访问接口端口号：{}", uri.getPort());
                        log.info("放文件接口URL：{}", uri.getPath());
                        log.info("访问接口的URL参数：{}", uri.getQuery());
                        log.info("访问时长：{}ms", (System.currentTimeMillis() - beginTime));
                        log.info("============================================");
                        System.out.println();
                    }
                }));
            }
        };
    }
}
